import { getToken, removeToken } from '@/utils/auth';
import { getUserInfo, getAllRoleUser } from '@/api/login';
import defAva from '@/assets/images/profile.jpg';
import { flatJSONList } from '@/utils/common.js';
// const isDev = import.meta.env.DEV;
const isDev = false;

const useUserStore = defineStore('user', {
  state: () => ({
    token: getToken(),
    name: '',
    avatar: '',
    roles: [],
    userStruct: [],
    orgUserList: [], // 这里并非用户列表，是组织架构列表
    userList: [], //这个是全用户的列表
    allDepartment: [], //部门列表
    permissions: [],
    allPermissions: [
      {
        id: 617,
        key: 'nav_system', // 系统导航（可查看所有系统）
        permission: 'navSystem:all:all'
      },
      {
        id: 619,
        key: 'set_system', // 座位图标（可编辑座位图）
        permission: 'seatSystem:operator:edit'
      },
      {
        id: 283,
        key: 'permission_page', // 权限设置
        permission: 'permissionPage:all:all'
      },
      {
        id: 777,
        key: 'system_setting', // 权限设置(可查看及编辑权限)
        permission: 'setting:operator:edit'
      },
      {
        id: 284,
        key: 'system_list', // 系统列表
        permission: 'systmeList:all:all'
      },
      {
        id: 778,
        key: 'system_page', // 系统列表(可查看及编辑系统列表)
        permission: 'systemList:operator:edit'
      }
    ]
  }),
  getters: {
    getUserById: state => id => {
      let item = state.userList.find(user => user.value == id);
      return item?.label ?? '';
    }
  },
  actions: {
    // 登录 oauth2页面会自动存储cookie
    login() {
      location.href = `/oauth2/login?callback=${location.href}`;
    },
    // 获取用户信息
    getInfo() {
      return new Promise(async resolve => {
        const userInfo = {
          user: {
            userName: 'admin',
            avatar: defAva
          },
          roles: ['admin'],
          permissions: ['*:*:*']
          // permissions: ['homePage:operator:user', 'homePage:purchaser:user']
        };

        // 生产环境
        if (!isDev) {
          const [{ data: info }, { data: RoleUser }] = await Promise.all([
            getUserInfo(),
            getAllRoleUser()
          ]);
          userInfo.user.userName = info.name;
          userInfo.roles = [];
          userInfo.permissions = this.fetchPermissions(info.authlist);
          this.userStruct = RoleUser.user_struct || [];
          this.SET_USER_LIST(RoleUser.user_struct);
        }

        const { user, roles, permissions } = userInfo;
        this.name = user.userName;
        this.avatar = user.avatar;
        this.roles = roles;
        this.permissions = permissions;
        resolve(userInfo);
      });
    },
    // 根据用户拥有的权限ID获取相应的页面权限
    fetchPermissions(permissionIDs) {
      const permissions = [];
      this.allPermissions.forEach(item => {
        if (permissionIDs?.includes(item.id)) {
          permissions.push(item.permission);
        }
      });
      return permissions;
    },
    // 设置用户列表
    SET_USER_LIST(value) {
      this.orgUserList = value || [];
      // 设置公司
      if (this.orgUserList && this.orgUserList.length) {
        let arr = JSON.parse(JSON.stringify(this.orgUserList));
        this.allDepartment =
          arr && arr.length ? this.setAllDepartment(arr) : [];
      }
      if (!value) return [];
      this.userList = flatJSONList(value, 'value', 'children').map(user => {
        return { ...user, name: user.label, id: user.value };
      });
    },
    setAllDepartment(data) {
      const arr = [];
      data.forEach(e => {
        if (e.value > -10000 && e.value < 0) {
          let children = e.children.filter(item => item.value < 0);
          e.children = children?.length > 0 ? children : null;
        }
        arr.push(e);
        if (e.children) {
          this.setAllDepartment(e.children);
        }
      });
      return arr;
    },
    // 退出系统
    logOut() {
      return new Promise(resolve => {
        this.token = '';
        this.roles = [];
        this.permissions = [];
        removeToken();
        resolve();
      });
    }
  }
});

export default useUserStore;
